<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>附件上传监听网速功能</title>
</head>
<body>
    <input type="file" class="myfile">
    进度：<progress value="0" max="100"></progress><span class="percent">0%</span>
    速度：<span class="speed">0b/s</span>
    <button>点击上传</button>
    <button>取消上传</button>
</body>
<script>
    let xhr = new XMLHttpRequest();
    let btns = document.querySelectorAll("button");
    let stime;  //开始上传时间
    let sloaded;  //文件大小
    btns[0].onclick = function(){
        let file = document.querySelector(".myfile").files[0];
        let form = new FormData();
        form.append("file",file);
        //xhr.open("post","http://127.0.0.1:8090/fengquan/mongodb-file/upload",true);
        xhr.open("post","http://q37f783146.qicp.vip/fengquan/mongodb-file/upload",true);
        xhr.onload = function(){
            console.log(xhr.responseText);
        }
        xhr.upload.onloadstart = function(){
            console.log("开始上传");
            stime = new Date().getTime();
            sloaded = 0;
        }
        xhr.upload.onprogress = function(evt){
             // console.log("正在上传");
            // console.log(evt);
            // 上传进度处理
            // 当前文件上传的大小 evt.loaded
            let percent = (evt.loaded/evt.total*100).toFixed(0);
            // console.log(percent);
            document.querySelector("progress").value = percent;
            document.querySelector(".percent").innerHTML = percent + "%";
            
            // 上传速度处理
            let endTime = new Date().getTime();
            // 时间差 由于时间差是毫秒  故要除以1000
            let dTime = (endTime - stime)/1000;
            // 当前时间内上传的文件大小  
            let dloaded = evt.loaded - sloaded;
            let speed = dloaded/dTime;
            let unit = "b/s";
            stime = new Date().getTime();
            sloaded = evt.loaded;
            if(speed/1024>1){
                unit = "kb/s";
                speed = speed/1024;
            }
            if(speed/1024>1){
                unit = "mb/s";
                speed = speed/1024;
            }
            // console.log(speed.toFixed(2));
            document.querySelector(".speed").innerHTML = speed.toFixed(2) + unit;
        }
        xhr.upload.onload = function(){
            console.log("上传成功");
        }
        xhr.upload.onloadend = function(){
            console.log("上传完成");
        }
        xhr.upload.onabort = function(){
            console.log("取消上传");
        }
        xhr.send(form);
    }
    btns[1].onclick = function(){
        xhr.abort();
    }
</script>
</html>